import axios from 'axios'
import store from '@/store/index.js'

axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/json charset=UTF-8'

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    const { user } =  store.getState()
    const { token } = user
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response.data
  },
  (error) => {
    // 对响应错误做点什么
    return Promise.reject(error)
  })

const servers = {
  get(url, params = {}) {
    params['t_' + new Date().getTime()] = Math.random()
    return axios.get(url, {
      params: params
    })
  },
  delete(url, params = {}) {
    params['t_' + new Date().getTime()] = Math.random()
    return axios.delete(url, {
      params: params
    })
  },
  post(url, data = {}) {
    return axios.post(url, data)
  },
  put(url, data = {}) {
    return axios.put(url, data)
  },
  patch(url, data = {}) {
    return axios.patch(url, data)
  }
}

export { servers as default }
